/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.poll.alarm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.common.core.util.CollectionUtils;
import com.hopes.bizz.poll.alarm.dto.PollAlarmExceptionDTO;
import com.hopes.bizz.poll.alarm.entity.PollAlarmExceptionEntity;
import com.hopes.bizz.poll.alarm.entity.PollAlarmHandleRecordEntity;
import com.hopes.bizz.poll.alarm.service.PollAlarmExceptionService;
import com.hopes.bizz.poll.alarm.service.PollAlarmHandleRecordService;
import com.hopes.bizz.poll.alarm.vo.PollAlarmExceptionVO;
import com.hopes.bizz.poll.common.constant.AlarmConstant;
import com.hopes.bizz.poll.monitor.entity.PollMonitorSiteEntity;
import com.hopes.bizz.poll.monitor.service.PollMonitorSiteService;
import com.hopes.bizz.poll.monitor.service.PollMonitorTypeService;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.core.util.StringUtils;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 异常报警
 *
 * @author daijie
 * @date 2023-09-21 15:56:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/alarmException")
@Tag(description = "alarmException", name = "异常报警管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class PollAlarmExceptionController {

    private final PollAlarmExceptionService pollAlarmExceptionService;
    private final PollMonitorSiteService pollMonitorSiteService;
    private final PollAlarmHandleRecordService pollAlarmHandleRecordService;
    private final PollMonitorTypeService pollMonitorTypeService;

    /**
     * 分页查询
     *
     * @param page               分页对象
     * @param pollAlarmException 异常报警
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('alarm_exception_view')")
    public R getpollAlarmExceptionPage(Page page, PollAlarmExceptionDTO pollAlarmException) {
        LambdaQueryWrapper<PollAlarmExceptionEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(PollAlarmExceptionEntity::getAlarmStatus);
        wrapper.orderByDesc(PollAlarmExceptionEntity::getAlarmTime);
        wrapper.ge(ObjectUtil.isNotNull(pollAlarmException.getBeginTime()), PollAlarmExceptionEntity::getAlarmTime, pollAlarmException.getBeginTime());
        wrapper.le(ObjectUtil.isNotNull(pollAlarmException.getEndTime()), PollAlarmExceptionEntity::getAlarmTime, pollAlarmException.getEndTime());
        wrapper.eq(ObjectUtil.isNotNull(pollAlarmException.getOrgId()), PollAlarmExceptionEntity::getOrgId, pollAlarmException.getOrgId());
        wrapper.eq(ObjectUtil.isNotNull(pollAlarmException.getMonitorSiteId()), PollAlarmExceptionEntity::getMonitorSiteId, pollAlarmException.getMonitorSiteId());

        wrapper.eq(ObjectUtil.isNotNull(pollAlarmException.getAlarmStatus()), PollAlarmExceptionEntity::getAlarmStatus, pollAlarmException.getAlarmStatus());
        wrapper.eq(ObjectUtil.isNotNull(pollAlarmException.getHandleStatus()), PollAlarmExceptionEntity::getHandleStatus, pollAlarmException.getHandleStatus());
        wrapper.eq(ObjectUtil.isNotNull(pollAlarmException.getAlarmLevel()), PollAlarmExceptionEntity::getAlarmLevel, pollAlarmException.getAlarmLevel());

        if (Objects.nonNull(pollAlarmException.getMonitorTypeMain())) {
            LambdaQueryWrapper<PollMonitorSiteEntity> monitorWrapper = new LambdaQueryWrapper<>();
            List<Integer> monitorTypeByMain = pollMonitorTypeService.getMonitorTypeByMain(pollAlarmException.getMonitorTypeMain());
            monitorWrapper.in(PollMonitorSiteEntity::getMonitorType, monitorTypeByMain);
            monitorWrapper.eq(Objects.nonNull(pollAlarmException.getTown()), PollMonitorSiteEntity::getTownId, pollAlarmException.getTown());
            List<Long> monitorIds = pollMonitorSiteService.list(monitorWrapper).stream().map(PollMonitorSiteEntity::getId).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(monitorIds)) {
                return R.ok(Collections.emptyList());
            }
            wrapper.in(CollectionUtils.isNotEmpty(monitorIds), PollAlarmExceptionEntity::getMonitorSiteId, monitorIds);
        }

        if (StringUtils.isNotBlank(pollAlarmException.getMonitorType())) {
            LambdaQueryWrapper<PollMonitorSiteEntity> monitorWrapper = new LambdaQueryWrapper<>();
            monitorWrapper.eq(PollMonitorSiteEntity::getMonitorType, pollAlarmException.getMonitorType());
            monitorWrapper.eq(Objects.nonNull(pollAlarmException.getTown()), PollMonitorSiteEntity::getTownId, pollAlarmException.getTown());
            List<Long> monitorIds = pollMonitorSiteService.list(monitorWrapper).stream().map(PollMonitorSiteEntity::getId).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(monitorIds)) {
                return R.ok(Collections.emptyList());
            }
            wrapper.in(CollectionUtils.isNotEmpty(monitorIds), PollAlarmExceptionEntity::getMonitorSiteId, monitorIds);
        }

        return R.ok(pollAlarmExceptionService.page(page, wrapper));
    }

    /**
     * 通过id查询异常报警
     *
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('alarm_exception_view')")
    public R getById(@PathVariable("id") Long id) {
        PollAlarmExceptionEntity entity = pollAlarmExceptionService.getById(id);
        PollAlarmExceptionVO vo = new PollAlarmExceptionVO();
        BeanUtils.copyProperties(entity, vo);

        LambdaQueryWrapper<PollAlarmHandleRecordEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PollAlarmHandleRecordEntity::getModuleCode, AlarmConstant.ALARM_TYPE_EXCEPTION);
        wrapper.eq(PollAlarmHandleRecordEntity::getAlarmId, id);
        wrapper.orderByDesc(PollAlarmHandleRecordEntity::getHandleTime);
        List<PollAlarmHandleRecordEntity> list = pollAlarmHandleRecordService.list(wrapper);
        vo.setHandleRecordList(list);
        return R.ok(vo);
    }

    /**
     * 新增异常报警
     *
     * @param pollAlarmException 异常报警
     * @return R
     */
    @Operation(summary = "新增异常报警", description = "新增异常报警")
    @SysLog("新增异常报警")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('alarm_exception_add')")
    public R save(@RequestBody PollAlarmExceptionEntity pollAlarmException) {
        return R.ok(pollAlarmExceptionService.save(pollAlarmException));
    }

    /**
     * 修改异常报警
     *
     * @param pollAlarmException 异常报警
     * @return R
     */
    @Operation(summary = "修改异常报警", description = "修改异常报警")
    @SysLog("修改异常报警")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('alarm_exception_edit')")
    public R updateById(@RequestBody PollAlarmExceptionEntity pollAlarmException) {
        return R.ok(pollAlarmExceptionService.updateById(pollAlarmException));
    }

    /**
     * 通过id删除异常报警
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除异常报警", description = "通过id删除异常报警")
    @SysLog("通过id删除异常报警")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('alarm_exception_del')")
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(pollAlarmExceptionService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     *
     * @param pollAlarmException 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('alarm_exception_export')")
    public List<PollAlarmExceptionEntity> export(PollAlarmExceptionEntity pollAlarmException) {
        return pollAlarmExceptionService.list(Wrappers.query(pollAlarmException));
    }
}